<template>
  <div class="shop-rent-detail" v-loading="loading">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="店铺名称">
        <el-tag type="primary" size="large">{{ rentInfo.shopName || '未知店铺' }}</el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="业主姓名">
        <span class="name-text">{{ rentInfo.ownerName || '未知业主' }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="租金金额">
        <span class="money-text">¥{{ formatMoney(rentInfo.rentAmount) }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="租金期间">
        {{ rentInfo.rentPeriod || '未知' }}
      </el-descriptions-item>
      <el-descriptions-item label="租金开始日期">
        {{ rentInfo.rentStartDate || '未知' }}
      </el-descriptions-item>
      <el-descriptions-item label="租金结束日期">
        {{ rentInfo.rentEndDate || '未知' }}
      </el-descriptions-item>
      <el-descriptions-item label="支付日期">
        {{ rentInfo.paymentDate || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="支付状态">
        <el-tag :type="getPaymentStatusTagType(rentInfo.paymentStatus)">
          {{ rentInfo.paymentStatusName || getPaymentStatusName(rentInfo.paymentStatus) }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="支付方式">
        {{ rentInfo.paymentMethod || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="收据号">
        {{ rentInfo.invoiceNumber || '-' }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">
        {{ formatDateTime(rentInfo.createTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="更新时间">
        {{ formatDateTime(rentInfo.updateTime) }}
      </el-descriptions-item>
      <el-descriptions-item label="备注" :span="2">
        {{ rentInfo.remark || '无' }}
      </el-descriptions-item>
    </el-descriptions>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <el-button 
        v-if="rentInfo.paymentStatus === 0" 
        type="success" 
        @click="handlePayment"
      >
        <el-icon><Money /></el-icon>
        立即支付
      </el-button>
      <el-button 
        v-if="rentInfo.paymentStatus === 0" 
        type="warning" 
        @click="handleRemind"
      >
        <el-icon><Bell /></el-icon>
        发送催缴
      </el-button>
      <el-button type="primary" @click="handleEdit">
        <el-icon><Edit /></el-icon>
        编辑记录
      </el-button>
      <el-button type="info" @click="handleClose">
        <el-icon><Close /></el-icon>
        关闭
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Money, Bell, Edit, Close } from '@element-plus/icons-vue'
import { shopRentApi } from '@/api/shop-rent'
import { shopApi } from '@/api/shop'
import type { ShopRentRecordDetail } from '@/api/shop-rent'

// Props
interface Props {
  rentId: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  payment: [rentId: number]
  remind: [rentId: number]
  edit: [rentId: number]
  close: []
}>()

// 响应式数据
const loading = ref(false)
const rentInfo = ref<ShopRentRecordDetail>({} as ShopRentRecordDetail)

// 生命周期
onMounted(() => {
  loadRentDetail()
})

// 方法
const loadRentDetail = async () => {
  // 参数校验
  if (!props.rentId || props.rentId <= 0) {
    ElMessage.error('租金记录ID无效')
    return
  }
  
  loading.value = true
  try {
    // 调用后端API获取租金记录详情
    const response = await shopRentApi.getRentRecordDetail(props.rentId)
    
    // 检查响应状态，遵循《Element Plus组件编码规范权威标准声明.md》规范
    // 根据《Element Plus组件编码规范权威标准声明.md》规范，API响应结构是扁平的
    if (response && response.message === '查询成功' && response.data) {
      const apiData = response.data
      console.log('API返回的原始数据:', apiData)
      
      // 数据字段映射和格式化，遵循《Element Plus组件编码规范权威标准声明.md》规范
      rentInfo.value = {
        id: apiData.id,
        shopId: apiData.shopId,
        shopName: apiData.shopName || '未知店铺',
        shopCode: apiData.shopCode || '',
        ownerId: apiData.ownerId,
        ownerName: apiData.ownerName || '未知业主',
        ownerPhone: apiData.ownerPhone || '',
        rentAmount: parseFloat(apiData.rentAmount) || 0,
        rentPeriod: apiData.rentPeriod || apiData.rentMonth || '',
        rentStartDate: apiData.rentStartDate || apiData.leaseStartDate || '',
        rentEndDate: apiData.rentEndDate || apiData.leaseEndDate || '',
        paymentDate: apiData.paymentDate || null,
        paymentStatus: parseInt(apiData.paymentStatus) || 0,
        paymentStatusName: getPaymentStatusName(parseInt(apiData.paymentStatus) || 0),
        paymentMethod: apiData.paymentMethod || null,
        paymentMethodName: apiData.paymentMethodName || null,
        invoiceNumber: apiData.invoiceNumber || null,
        remark: apiData.remark || null,
        createTime: apiData.createTime || '',
        updateTime: apiData.updateTime || ''
      }
      
      // 如果缺少店铺名称或业主姓名，尝试获取店铺信息
      if ((!apiData.shopName || !apiData.ownerName) && apiData.shopId) {
        await loadShopInfo(apiData.shopId)
      }
      
      console.log('处理后的租金详情数据:', rentInfo.value)
    } else {
      const errorMsg = response?.message || '获取租金详情失败'
      ElMessage.error(errorMsg)
      console.error('API返回错误:', response)
    }
  } catch (error: any) {
    console.error('加载租金详情失败:', error)
    
    // 根据错误类型提供不同的错误信息，遵循《Element Plus组件编码规范权威标准声明.md》规范
    let errorMessage = '加载租金详情失败'
    if (error.response) {
      // 服务器响应错误
      errorMessage = `服务器错误: ${error.response.status} - ${error.response.data?.message || '未知错误'}`
    } else if (error.request) {
      // 网络错误
      errorMessage = '网络连接失败，请检查网络设置'
    } else {
      // 其他错误
      errorMessage = `请求失败: ${error.message || '未知错误'}`
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

const handlePayment = () => {
  emit('payment', props.rentId)
}

const handleRemind = () => {
  emit('remind', props.rentId)
}

const handleEdit = () => {
  emit('edit', props.rentId)
}

const handleClose = () => {
  emit('close')
}

// 重新加载数据
const reloadData = () => {
  loadRentDetail()
}

// 获取店铺信息
const loadShopInfo = async (shopId: number) => {
  try {
    console.log('获取店铺信息，店铺ID:', shopId)
    const response = await shopApi.getShopDetail(shopId)
    
    // 根据《Element Plus组件编码规范权威标准声明.md》规范，API响应结构是扁平的
    if (response && response.message === '查询成功' && response.data) {
      const shopData = response.data
      console.log('店铺信息获取成功:', shopData)
      
      // 更新店铺信息，遵循《Element Plus组件编码规范权威标准声明.md》规范
      if (shopData.shopName) {
        rentInfo.value.shopName = shopData.shopName
      }
      if (shopData.shopCode) {
        rentInfo.value.shopCode = shopData.shopCode
      }
      
      // 如果有业主信息，也更新
      if (shopData.ownerName) {
        rentInfo.value.ownerName = shopData.ownerName
      }
      if (shopData.ownerPhone) {
        rentInfo.value.ownerPhone = shopData.ownerPhone
      }
      
      console.log('更新后的租金详情数据:', rentInfo.value)
    } else {
      console.warn('获取店铺信息失败:', response?.message)
    }
  } catch (error: any) {
    console.warn('获取店铺信息异常:', error.message)
  }
}

// 暴露方法给父组件
defineExpose({
  reloadData
})

// 工具方法
const getPaymentStatusTagType = (status: number) => {
  const typeMap = {
    0: 'danger',  // 未支付
    1: 'success', // 已支付
    2: 'warning'  // 逾期
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

// 获取支付状态名称，遵循《系统状态枚举权威标准声明.md》
const getPaymentStatusName = (status: number) => {
  const statusMap = {
    0: '未支付',
    1: '已支付', 
    2: '逾期'
  }
  return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 安全的日期时间格式化函数，遵循《Element Plus组件编码规范权威标准声明.md》规范
const formatDateTime = (dateTime: string | null | undefined): string => {
  try {
    if (!dateTime || dateTime === '' || dateTime === null || dateTime === undefined) {
      return '-'
    }
    
    // 处理后端返回的日期时间格式 "2025-10-09 16:08:08"
    const date = new Date(dateTime)
    
    // 检查日期是否有效
    if (isNaN(date.getTime())) {
      console.warn('无效的日期时间:', dateTime)
      return '-'
    }
    
    // 格式化日期时间
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    console.warn('formatDateTime error:', error, 'dateTime:', dateTime)
    return '-'
  }
}

// 安全的金额格式化函数，遵循《Element Plus组件编码规范权威标准声明.md》规范
const formatMoney = (amount: any): string => {
  try {
    if (amount === null || amount === undefined || amount === '') {
      return '0.00'
    }
    
    // 确保是数字类型
    const num = typeof amount === 'number' ? amount : parseFloat(amount)
    
    // 检查是否为有效数字
    if (isNaN(num) || !isFinite(num)) {
      return '0.00'
    }
    
    // 格式化数字，保留两位小数
    return num.toFixed(2)
  } catch (error) {
    console.warn('formatMoney error:', error, 'amount:', amount)
    return '0.00'
  }
}
</script>

<style scoped>
.shop-rent-detail {
  padding: 20px;
}

.action-buttons {
  margin-top: 30px;
  text-align: center;
}

.action-buttons .el-button {
  margin: 0 8px;
}

.name-text {
  font-weight: 600;
  color: #303133;
  font-size: 16px;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>
